var express = require('express');
var router = express.Router();
const { packRes } = require('../utils/packRes')
const multiparty = require('multiparty')
const { log } = require("debug");
const connection = require('../mysql')
const path = require('path')
const fs = require('fs')
const fullPath = './public/images/banner/'


router.get('/', function (req, res, next) {
    const { page = 1, limit = 5 } = req.query;
    const offset = (page - 1) * limit;
    connection.query('SELECT COUNT(*) as total FROM banner', function (error, results, fields) {
        if (error) throw error;
        const total = results[0].total;
        connection.query('SELECT * FROM banner LIMIT ?, ?', [offset, limit * 1], function (error, results, fields) {
            if (error) throw error;
            const count = results.length;
            const pages = Math.ceil(total / limit);
            res.status(200).send(packRes(200, { results, count, total, pages }));
            return;
        });
    });
});



router.post('/update', function (req, res, next) {
    const { id, name, target } = req.body;

    const sql = `SELECT * FROM banner WHERE id='${id}'`;
    connection.query(sql,(err,results)=>{
        if (err) throw error;
        if(!results[0]){
            res.status(200).send(packRes(400, null,'找不到该数据'));
        }
        const updateSQL = `UPDATE banner SET name = ?, target = ? WHERE id = ?`;
        connection.query(updateSQL, [name, target, id], function (error) {
            if (error) throw error;
            res.status(200).send(packRes(200, { id, name, target, url:results[0].url }));
        });
    })


});



router.post('/add', function (req, res, next) {
    console.log('8888',req.body);
    const from = new multiparty.Form();
    from.uploadDir = fullPath;
    from.parse(req, (err, files, file) => {
        console.log(err, files, file)
        if (err || !file.file[0]) {
            res.status(200).send(packRes(400, '', '图片上传失败'));
            return;
        }
        let { name: [name], target: [target] } = files;
        let url = `${req.protocol}://${req.headers.host}${file.file[0].path.replace('public', '')}`;

        console.log(666666);
        connection.query('INSERT INTO banner (name, target, url) VALUES (?, ?, ?)', [name, target, url], function (error, results, fields) {
            if (error) throw error;
            res.status(200).send(packRes(200, { name, target, url }));
            return;
        });
    });
});
router.post('/delete/:id', function (req, res, next) {
    const id = req.params.id;
    console.log(id)
    const selectSQL = `SELECT url FROM banner WHERE id = ?`;
    connection.query(selectSQL, [id], function (error, results, fields) {
        if (error) throw error;
        const url = results[0].url;
        const deleteSQL = `DELETE FROM banner WHERE id = ?`;
        connection.query(deleteSQL, [id], function (error, results, fields) {
            if (error) throw error;
            const filePath = `${fullPath}${path.basename(url)}`;
            fs.unlink(filePath, function (err) {
                if (err) {
                    console.error(err);
                    res.status(500).send(packRes(500, '', '服务端异常'));
                    return;
                }
            });
            res.status(200).send(packRes(200, '', '删除成功'));
        });
    });
});
router.post('/edit/:id', function (req, res, next) {
    const id = req.params.id;
    console.log('得到的ID', id)
    const selectSQL = `SELECT url FROM banner WHERE id = ?`;
    connection.query(selectSQL, [id], function (error, results, fields) {
        if (error) throw error;
        if (results.length === 0) {
            res.status(200).send(packRes(400, '', '该ID不存在'))
            return;
        }
        const url = results[0].url;
        const from = new multiparty.Form();
        from.uploadDir = fullPath;
        from.parse(req, (err, files, file) => {
            console.log(err, files, file)
            if (err) {
                res.status(200).send(packRes(400, '', '图片上传失败'));
                return;
            }
            let { name: [name], target: [target] } = files;
            let editUrl = url;
            if (file.file) {
                editUrl = `${req.protocol}://${req.headers.host}${file.file[0].path.replace('public', '')}`;
                const filePath = `${fullPath}${path.basename(url)}`;
                fs.unlink(filePath, function (err) {
                    if (err) {
                        console.error(err);
                        res.status(500).send(packRes(500, '', '服务端异常'));
                        return;
                    }
                });
            }
            const updateSQL = `UPDATE banner SET name = ?, target = ?, url = ? WHERE id = ?`;
            connection.query(updateSQL, [name, target, editUrl, id], function (error, results, fields) {
                if (error) throw error;
                res.status(200).send(packRes(200, { id, name, target, url: editUrl }));
            });
        });
    });
});


module.exports = router;
